var AsyncModal = (() => {
    // 私有状态管理
    const state = {
        currentModal: null,
        selectedRow: null,
        selectedValue: null
    };

    // 工具方法集合
    const utils = {
        log: (...args) => console.log('[AsyncModal]', ...args),
        createElement: (tag, { className, parent, textContent, styles } = {}) => {
            const el = document.createElement(tag);
            if (className) el.className = className;
            if (textContent) el.textContent = textContent;
            if (parent) parent.appendChild(el);
            if (styles) Object.assign(el.style, styles);

            return el;
        },
        createStyleSheet: () => {
            if (!document.getElementById('async-modal-style')) {
                const style = document.createElement('style');
                style.id = 'async-modal-style';
                style.textContent = `
                    .async-modal-mask {
                        position: fixed;  
                        top: 40%;
                        right: 5%;

                        display: flex;
                        flex-direction: column;
                        justify-content: space-evenly; 
                        align-items: center; 
                        z-index: 9999;
                        opacity: 0;
                        transition: opacity 0.2s;
                        background: rgba(0,0,0,0); 
                    }
                    .async-modal-mask.show {
                        opacity: 1; 
                    }
                    .async-modal-content {
                        background: white;
                        padding: 20px;
                        border-radius: 10px; 
                        opacity: 0; 
                        box-shadow: 0 4px 20px rgba(0,0,0,0.2);
                        min-width: 200px; 
                    }
                    .async-modal-mask.show .async-modal-content {
                        transform: translateY(0);
                        opacity: 1;
                    }
                    .async-modal-header {
                        text-align: center;
                        font-weight: 600;
                        margin-bottom: 15px;
                        padding-bottom: 10px;
                        border-bottom: 1px solid #eee;
                    }
                    .async-modal-footer {
                        margin-top: 20px;
                        text-align: center;
                    }
                    .async-modal-btn {
                        padding: 8px 16px;
                        margin-left: 10px;
                        border: none;
                        border-radius: 4px;
                        cursor: pointer;
                        background: #007bff;
                        color: white;
                        transition: opacity 0.2s;
                    }
                    .async-modal-btn:hover {
                        opacity: 0.9;
                    }
                    .async-modal-btn-cancel {
                        background: #6c757d;
                    }
                    .async-modal-input {
                        width: 100%;
                        padding: 8px;
                        margin: 10px 0;
                        border: 1px solid #ddd;
                        border-radius: 4px;
                        box-sizing: border-box;
                    }
                    .async-modal-table-wrap {
                        max-height: 400px;
                        overflow-y: auto;
                        margin: 10px 0;
                    }
                    .async-modal-table {
                        width: 100%;
                        border-collapse: collapse;
                    }
                    .async-modal-table th,
                    .async-modal-table td {
                        min-width: 50px;
                        padding: 12px;
                        border-bottom: 1px solid #eee;
                        text-align: left;
                    }
                    .async-modal-table th {
                        background: #f8f9fa;
                        font-weight: 600;
                    }
                    .async-modal-table-row:hover {
                        background-color: #f8f9fa;
                        cursor: pointer;
                    }
                    .async-modal-table-row.selected {
                        background-color: #e3f2fd;
                    }
                    .async-modal-radio {
                        margin-right: 10px;
                        transform: scale(1.2);
                    }`;
                document.head.appendChild(style);
            }
        }
    };

    // 弹窗基类
    class BaseModal {
        constructor(options) {
            this.options = options;
            this.resolve = null;
            this.reject = null;
        }
        initElements() {
            this.mask = utils.createElement('div', { className: 'async-modal-mask', parent: document.body });
            this.content = utils.createElement('div', { className: 'async-modal-content', parent: this.mask });
            this.createHeader();
            this.createBody();
            this.createFooter();
        }

        createHeader() {
            if (!this.options.title) return;
            this.header = utils.createElement('div', {
                className: 'async-modal-header',
                parent: this.content,
                textContent: this.options.title
            });
        }

        createBody() {
            this.body = utils.createElement('div', { className: 'async-modal-body', parent: this.content });
            this.renderBodyContent();
        }
        // 新增：基础文本渲染逻辑
        renderBodyContent() {
            if (this.options.content) {
                this.body.textContent = this.options.content;
            }
        }
        createFooter() {
            this.footer = utils.createElement('div', { className: 'async-modal-footer', parent: this.content });
            this.createButtons();
        }

        createButtons() {
            const buttons = this.getButtonsConfig();
            this.buttons = buttons.map(btnConfig => {
                const btn = utils.createElement('button', {
                    className: `async-modal-btn ${btnConfig.className || ''}`,
                    parent: this.footer,
                    textContent: btnConfig.text
                });
                btn.addEventListener('click', () => this.handleButtonClick(btnConfig.action));
                return btn;
            });
        }
        getConfirmResult() { return false; }
        handleButtonClick(action) {
            let result = false; // 默认失败返回false
            if (action === 'confirm') {
                result = this.getConfirmResult() || false; // 确保至少返回false
            }
            this.resolve(result);
            this.close();
        }

        getButtonsConfig() {
            const baseButtons = [
                { text: '取消', action: 'cancel', className: 'async-modal-btn-cancel' },
                { text: '确认', action: 'confirm' }
            ];
            return this.options.buttons || baseButtons;
        }

        close() {
            this.mask.classList.remove('show');
            setTimeout(() => {
                if (this.mask.parentNode) document.body.removeChild(this.mask);
                state.currentModal = null;
            }, 200);
        }

        show() { 
            return new Promise((resolve, reject) => {
                utils.createStyleSheet();
                setTimeout(() => this.mask.classList.add('show'), 10);
                this.initElements();
                this.resolve = resolve;
                this.reject = reject;
            });
        }
    }

   // 确认弹窗专用类
    class ConfirmModal extends BaseModal {
        getConfirmResult() {
            return true; // 确认操作返回true
        }
    }
    // 表格选择弹窗
    class TableSelectModal extends BaseModal {
        renderBodyContent() {
            if (!this.options.data?.length) return;

            this.tableWrap = utils.createElement('div', {
                className: 'async-modal-table-wrap',
                parent: this.body
            });

            this.table = utils.createElement('table', {
                className: 'async-modal-table',
                parent: this.tableWrap
            });

            this.renderTableHead();
            this.renderTableBody();
        }

        renderTableHead() {
            const thead = utils.createElement('thead', { parent: this.table });
            const headerRow = utils.createElement('tr', { parent: thead });

            this.options.columns.forEach(col => {
                utils.createElement('th', {
                    parent: headerRow,
                    textContent: col.title || col.key
                });
            });
        }

        renderTableBody() {
            this.tbody = utils.createElement('tbody', { parent: this.table });

            this.options.data.forEach((rowData, index) => {
                const tr = utils.createElement('tr', {
                    className: 'async-modal-table-row',
                    parent: this.tbody
                });

                this.options.columns.forEach(col => {
                    const td = utils.createElement('td', { parent: tr });
                    if (col.type === 'radio') {
                        this.createRadioInput(td, rowData, index);
                    } else {
                        td.textContent = this.getCellContent(col, rowData);
                    }
                });

                tr.addEventListener('click', () => this.handleRowClick(rowData, tr));
            });
        }

        createRadioInput(td, rowData, index) {
            const radio = utils.createElement('input', {
                parent: td,
                styles: { marginRight: '10px', transform: 'scale(1.2)' }
            });
            radio.type = 'radio';
            radio.name = 'async-modal-radio-group';  
            if(index === 0){
                radio.checked = true;
                state.selectedRow = rowData;  // 默认选中第一行
            }

            radio.addEventListener('change', () => this.handleRadioChange(radio, rowData));
        }

        handleRowClick(rowData, tr) {
            if (event.target.type !== 'radio') {
                const radio = tr.querySelector('input[type="radio"]');
                radio.checked = true;
                this.handleRadioChange(radio, rowData);
            }
        }

        handleRadioChange(radio, rowData) {
            console.log('Radio changed:', radio.value,rowData);
            state.selectedRow = rowData;
            document.querySelectorAll('.async-modal-table-row').forEach(row =>
                row.classList.toggle('selected', row === radio.closest('tr'))
            );
        }

        getCellContent(col, rowData) {
            return col.renderCell ? col.renderCell(rowData) : rowData[col.field];
        }

        getConfirmResult() {
            return state.selectedRow || false;
        }
    }

    // 输入弹窗
    class PromptModal extends BaseModal {
        renderBodyContent() {
            this.input = utils.createElement('input', {
                className: 'async-modal-input',
                parent: this.body,
                styles: { width: '100%', padding: '8px', margin: '10px 0' }
            });
            this.input.type = this.options.inputType || 'text';
            this.input.placeholder = this.options.placeholder || '';
        }

        getConfirmResult() {
            return this.input.value.trim() || false;
        }
    }

    // 工厂方法
    const modalFactory = {
        alert: (options) => new BaseModal({
            ...options,
            type: 'alert',
            buttons: [{ text: options.okText || '确定', action: 'confirm' }]
        }).show(),

        confirm: (options) => new ConfirmModal({
            ...options,
            type: 'confirm'
        }).show(),

        prompt: (options) => new PromptModal({
            ...options,
            type: 'prompt'
        }).show(),

        tableSelect: (options) => new TableSelectModal({
            ...options,
            type: 'tableSelect'
        }).show()
    };

    return {
        alert: (options) => modalFactory.alert(typeof options === 'string' ? { content: options } : options),
        confirm: (options) => modalFactory.confirm(options),
        prompt: (options) => modalFactory.prompt(options),
        tableSelect: (options) => modalFactory.tableSelect(options)
    };
})();

 

 /*
// 测试alert
AsyncModal.alert('操作成功！').then(() => {
    console.log('Alert确认回调');
});

// 测试confirm
AsyncModal.confirm({
    content: '确定要删除吗？',
    confirmText: '狠心删除',
    cancelText: '再想想'
}).then(() => {
    console.log('Confirm确认回调');
}).catch(() => {
    console.log('Confirm取消回调');
});

// 测试prompt
AsyncModal.prompt({
    title: '请输入用户名',
    placeholder: '请输入用户名',
    confirmText: '确定',
    cancelText: '取消'
}).then(value => {
    console.log('Prompt确认回调', value);
}).catch(() => {
    console.log('Prompt取消回调');
});

// 测试tableSelect
AsyncModal.tableSelect({
    title: '选择一行',
    columns: [
        { type: 'radio', field: 'value', title: '选择' },
        { field: 'id', title: 'ID' },
        { field: 'name', title: '名称' },
        { field: 'value', title: '值' }
    ],
    data: [
        { id: 1, name: '选项1', value: 'Value1' },
        { id: 2, name: '选项2', value: 'Value2' },
        { id: 3, name: '选项3', value: 'Value3' }, { id: 1, name: '选项1', value: 'Value1' },
        { id: 2, name: '选项2', value: 'Value2' },
        { id: 3, name: '选项3', value: 'Value3' }, { id: 1, name: '选项1', value: 'Value1' },
        { id: 2, name: '选项2', value: 'Value2' },
        { id: 3, name: '选项3', value: 'Value3' }, { id: 1, name: '选项1', value: 'Value1' },
        { id: 2, name: '选项2', value: 'Value2' },
        { id: 3, name: '选项3', value: 'Value3' }
    ],
    valueKey: 'id'
}).then(selectedRow => {
    console.log('TableSelect确认回调', selectedRow);
}).catch(() => {
    console.log('TableSelect取消回调');
});
 */ 